import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from aws_model.athena_submit import submit
from delete import delete_data
from base_class.inspect_logging import print_to_log
import datetime
import json
from aws_model.aws_stepfunc import send_task_success, send_task_failure


def kyd_ods(event):
    date = event.get('p_date')
    if not date:
        date =datetime.datetime.today().strftime('%Y-%m-%d')
    table_name = sys._getframe().f_code.co_name
    date = datetime.datetime.strptime(date, '%Y-%m-%d')
    # 删除前第二天的数据(kyd数据original延迟两天)
    date = (date - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
    delete_data(table_name, date)
    sql = f'''INSERT INTO ods.kyd_ods 
                    select * from 
                    ( 
                        select 
                            hfmonth, COALESCE(TRY(CAST(objectid AS bigint)),null) as objectid, 
                            COALESCE(TRY(CAST(fws AS bigint)),null) as fws, 
                            fwst, statuser, status, statsysf, status1, serviceorg, serviceorgrep, bsc, 
                            COALESCE(TRY(CAST(zzfld000002 AS integer)),null) as zzfld000002, zzfld000002t, zzfld000003,
                            zzfld000003t, zzfld000001, zzfld000001t, zzfld00002f, zzfld00002ft, zzfld00000q, 
                            zzfld00002g, zzfld00002gt, gzdl, wxdm, wxms, description, zzfld000036, zzfld00000b, 
                            cpxl, kh, COALESCE(TRY(CAST(zzfld00002i AS integer)),null) as zzfld00002i, zzfld000044, 
                            zzfld000044t, COALESCE(TRY(CAST(hsj AS bigint)),null) as hsj, hsjms, 
                            COALESCE(TRY(CAST(hsjquantity AS decimal(19, 1))),null) as hsjquantity, 
                            COALESCE(TRY(CAST(hxj AS bigint)),null) as hxj, hxjms, 
                            COALESCE(TRY(CAST(hxjquantity AS decimal(19, 1))),null) as hxjquantity, createdat,
                            COALESCE(TRY(CAST(date9 AS bigint)),null) as date9, 
                            COALESCE(TRY(CAST(fwzq AS integer)),null) as fwzq,
                            COALESCE(TRY(CAST(cqzq AS integer)),null) as cqzq, 
                            concat(substr(createdat, 1, 4) ,'-',substr(createdat, 5, 2),'-',substr(createdat, 7, 2)) as p_date 
                            from 
                        original.kyd_all
                    ) 
                where 
                    date(p_date) >= cast ('{date}' as date)
                and 
                    date(p_date) < (cast ('{date}' as date) + interval '1' day )
                 '''
    print_to_log(sql)
    athena_response = submit(sql)
    print_to_log("athena_response: ", athena_response)
    output = {"msg": f"{table_name} submit ok", "Payload": {}}
    output = json.dumps(output)
    step_response = send_task_success(tasktoken, output)
    print_to_log("step_response: ", step_response)


if __name__ == '__main__':
    try:
        event = json.loads(sys.argv[1])
        tasktoken = event.get('TaskToken')
        kyd_ods(event)
    except Exception as e:
        print_to_log("athena_submit 失败")
        print_to_log("原因： ", str(e))
        send_task_failure(str(e), f'执行{sys._getframe().f_code.co_filename}错误', tasktoken)

